package core

import (
	"errors"
	"fmt"
	"run_order/model"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/spf13/viper"
)

type userStdClaims struct {
	model.JwtStruct
	jwt.StandardClaims
}
type wxClaims struct {
	model.WxJwtStruct
	jwt.StandardClaims
}

var (
	secret = []byte(viper.GetString("token.secret"))
)
var (
	wx_secret = []byte(viper.GetString("token.secret"))
)

// 生成token
func GetToken(user model.UserBasic) (string, error) {
	tokenExpireTime := time.Duration(viper.GetInt64("token.expireTime")) * time.Hour
	issuer := viper.GetString("token.issuer")
	fmt.Println("后台获取的过期时间：", tokenExpireTime, viper.GetInt64("token.expireTime"))
	jwtStruct := model.JwtStruct{
		ID:         user.ID,
		Name:       user.UserName,
		Phone:      user.Phone,
		Email:      user.Email,
		ExpireTime: time.Now().Add(tokenExpireTime).Unix(),
	}
	c := userStdClaims{
		jwtStruct,
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(tokenExpireTime).Unix(),
			Issuer:    issuer,
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	return token.SignedString(secret)
}

// 解析token
func ParseToken(tokenStr string) (userStdClaims, error) {
	pJwt := userStdClaims{}
	token, err := jwt.ParseWithClaims(tokenStr, &pJwt, func(t *jwt.Token) (interface{}, error) {
		return secret, nil
	})
	//token.Valid=true代表token有效
	if err != nil || !token.Valid {
		err = errors.New("token无效")
	}
	return pJwt, err
}

// 生成微信token
func GetWxToken(user model.WxUser) (string, error) {
	wxTokenExpireTime := time.Duration(viper.GetInt64("token.expireTime")) * time.Hour
	issuer := viper.GetString("token.issuer")
	fmt.Println("生成微信token使用的user：", user)
	jwtStruct := model.WxJwtStruct{
		UserName:   user.UserName,
		Phone:      user.Phone,
		Sex:        user.Sex,
		OpenId:     user.OpenId,
		ExpireTime: time.Now().Add(wxTokenExpireTime).Unix(),
	}
	fmt.Println("过期时间1：", wxTokenExpireTime, viper.GetInt64("token.expireTime"))
	c := wxClaims{
		jwtStruct,
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(wxTokenExpireTime).Unix(),
			Issuer:    issuer,
		},
	}
	fmt.Println("实际过期时间：", time.Now().Add(wxTokenExpireTime).Unix())
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	return token.SignedString(wx_secret)
}

// 解析微信token
func ParseWxToken(tokenStr string) (wxClaims, error) {
	pJwt := wxClaims{}
	token, err := jwt.ParseWithClaims(tokenStr, &pJwt, func(t *jwt.Token) (interface{}, error) {
		return wx_secret, nil
	})
	if err != nil || !token.Valid {
		err = errors.New("token是无效的")
	}
	return pJwt, err

}
